//
//  GalleryImageController.m
//  RtspClient
//
//  Created by qi tan on 2024/3/4.
//  Copyright © 2024 Andres Rojas. All rights reserved.
//

#import "GalleryImageController.h"
#import "VideoCell.h"


@interface GalleryImageController () <UITableViewDataSource, UITableViewDelegate >

// 图片列表
@property (weak, nonatomic) IBOutlet UITableView *tableView01;

// 数据源--图片
@property(nonatomic, strong) NSMutableArray *images; // 截图列表
// 全屏查看大图
@property (weak, nonatomic)  UIButton *btnCover;
@end


@implementation GalleryImageController
#pragma mark ---懒加载页面数据---
- (void)initDataList {
    NSString *docPath =  NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSFileManager *fmgr = [NSFileManager defaultManager];
    NSArray *subPaths = [fmgr subpathsAtPath:docPath]; // 获取文件列表

    NSLog(@"-------开始排序: 倒序显示所有文件-------");
    NSArray *sorted = [subPaths sortedArrayUsingComparator:^NSComparisonResult(NSString *firstPath,NSString *secondPath) {
        NSString *firstUrl = [docPath stringByAppendingPathComponent:firstPath];
        NSString *secondUrl = [docPath stringByAppendingPathComponent:secondPath];
        
        NSDictionary *firstFileInfo = [[NSFileManager defaultManager]
                                       attributesOfItemAtPath:firstUrl error:nil];
        NSDictionary *secondFileInfo = [[NSFileManager defaultManager]
                                        attributesOfItemAtPath:secondUrl error:nil];
        id firstData = [firstFileInfo objectForKey:NSFileCreationDate];
        id secondData = [secondFileInfo objectForKey:NSFileCreationDate];
        return [secondData compare:firstData];
    }];
    
    // 分别处理视频列表数据，图片列表数据
    NSMutableArray * array01 = [NSMutableArray array];
    for (NSString *fileName2 in sorted) {
        if([fileName2 hasSuffix:@".png"]) { // 图片
            [array01 addObject:fileName2];
        }
    }
    _images = array01;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    [self setTitle: NSLocalizedString(@"gallery", nil)];
    [self initDataList]; // 初始化数据
    self.tableView01.dataSource = self;
    self.tableView01.delegate = self;
    self.tableView01.rowHeight = 94;
    [self.tableView01 reloadData];
}

#pragma mark 列表侧滑删除
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if(editingStyle == UITableViewCellEditingStyleDelete) {
        // 删除item操作。
        [self showDeleteDialog:tableView withIndexPath: indexPath];
    }
}
// TODO 无效方法 delete
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:( NSIndexPath *)indexPath{
    return NSLocalizedString(@"delete", nil);
}

// 二次弹框，确认删除 sure_to_delete
- (void)showDeleteDialog:(UITableView *)tableView withIndexPath:(NSIndexPath *) indexPath {
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"prompt", nil)
        message:NSLocalizedString(@"sure_to_delete", nil)
        preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", nil)
                                                           style:UIAlertActionStyleCancel
                                                         handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"取消");
    }];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"confirm", nil)
                                                       style:UIAlertActionStyleDefault
                                                     handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"row: %zd", indexPath.row);
            [self deleteShaHeFile:self.images[indexPath.row]];
            [self.images removeObjectAtIndex:indexPath.row];
            [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationTop];
    }];
    [alertController addAction:cancelAction];
    [alertController addAction:okAction];
    [self presentViewController:alertController animated:YES completion:nil];
}
// 删除沙盒中的图片
- (void)deleteShaHeFile:(NSString *)fileName {
    NSString *docPath =  NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSFileManager *fmgr = [NSFileManager defaultManager];
    NSString *fileUrl = [docPath stringByAppendingPathComponent:fileName];
    BOOL result = [fmgr removeItemAtPath:fileUrl error:nil];
    if(result){
        NSLog(@"删除元素: %@", fileName);
    } else {
        NSLog(@"删除失败: %@", fileName);
    }
}


#pragma mark 列表数据源方法。
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.images.count;
}
// 列表item的显示样式。bug
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    // 1.获取模型数据
    NSString *model = nil;
    VideoCell *cell = nil;
    // 图片tab
    if(indexPath.row < self.images.count){
        model = self.images[indexPath.row];
        cell = [VideoCell videoImageCellWithTableView:self.tableView01];
    }
    
    // 使用xib方式，创建自定义view
    cell.item = model;
    return cell;
}

#pragma mark 列表cell选择
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    NSString * name = self.images[indexPath.row];
    NSLog(@"选择image: %@", name);
    [self showImageFullScreen:name];;
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}


#pragma mark 全屏显示图片
- (void)showImageFullScreen:(NSString *)fileName {
    UIButton *btnCover = [[UIButton alloc] init];
    btnCover.frame = self.view.frame;
    btnCover.backgroundColor = [UIColor blackColor];
    btnCover.alpha = 0.0;
    [self.view addSubview:btnCover];
    self.btnCover = btnCover;
    // 阴影添加点击事件
    [btnCover addTarget:self action:@selector(smallImage) forControlEvents:UIControlEventTouchUpInside];
    
    NSString *docPath =  NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString *filePath = [docPath stringByAppendingPathComponent:fileName];
    // 把模型的数据，设置给子控件。
    UIImage *image = [[UIImage alloc] initWithContentsOfFile:filePath];
    UIImageView *bigImage = [[UIImageView alloc] initWithImage:image];
    bigImage.frame = CGRectZero;
    [btnCover addSubview: bigImage];
    
    CGFloat iconW = self.view.bounds.size.width;
    CGFloat iconH = 0.75 * iconW;
    CGFloat iconX= 0;
    CGFloat iconY = (self.view.bounds.size.height - iconH) * 0.5;
    
    [UIView animateWithDuration:0.5 animations:^{
            btnCover.alpha = 1;
            bigImage.frame = CGRectMake(iconX, iconY, iconW, iconH);
        }];
}

- (void)smallImage {
    // 大图变小。移除。
    NSLog(@"smallImage");
    [self.btnCover removeFromSuperview];
    self.btnCover = nil;
}


@end
